import serial
import RadarCameraDetction.utils.RadarInstructCode as rd
import RadarCameraDetction.utils.AnalysisData as ad
import RadarCameraDetction.utils.PcCameraCalibration as cc
import RadarCameraDetction.utils.USBCameraCalibration as uc
import serial.tools.list_ports
import logging
import time
import sys
import os

def init():
    print(os.getcwd())
    sys.path.append(os.getcwd())
    logging.basicConfig(level = logging.INFO,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    global logger
    logger = logging.getLogger(__name__)


def CheckSerial():
    plist = list(serial.tools.list_ports.comports())
    if len(plist) <= 0:
        return '',False
    else:
        plist_0 = list(plist[0])
        # print('COM: ',plist_0)
        return plist_0[0],True


def Open(Baud):
    name, err = CheckSerial()
    if err == False:
        logger.warning("No Serial")
        return None, False
    ser = serial.Serial(name, Baud, timeout=None)
    ser.close()

    try:
        ser.open()
    except:
        logger.warning("something error when opening the serial")
        return None, False

    assert ser.isOpen()

    # 设置好波特率
    SetBaudCode = rd.GetBaudCode(Baud)
    ser.write(SetBaudCode)
    retdata = ser.read(6)
    # print(retdata[2:].hex())
    # print(SetBaudCode[2:].hex())
    if retdata[2:].hex() != SetBaudCode[2:].hex():
        logger.warning("SetBaud is False")
        return None,False
    else:
        # # 打开雷达
        ser.write(rd.OpenRadarCode)
        retdata = ser.read(6)
        return ser, True

def GetData(ser):
    RadarTarget = {}
    detectlist = []
    if ser.isOpen == False:
        logger.warning("Radar is closed,please check")
        return None
    else:
        ser.write(rd.GetRadarResult)
        times = int(time.time())
        _ = ser.read(4)
        detectnum = ord(ser.read(1))
        for i in range(detectnum):
            infos = ser.read(8)
            RadarTag = ad.AnalysisRadarRetData(infos)
            RadarTag = uc.Radar2Camera(RadarTag)
            detectlist.append(RadarTag)
        _ = ser.read(3)
        RadarTarget["RadarTagnum"] = detectnum
        RadarTarget["RadarTaglist"] = detectlist
        RadarTarget["Time"] = times
        return RadarTarget

def Close(ser):
    ser.write(rd.CloseRadarCode)
    ser.close()


